package com.freeager.atomikos.test.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.freeager.atomikos.test.mapper.ds1.UserMapper;
import com.freeager.atomikos.test.model.User;
import com.freeager.atomikos.test.service.BalanceLogService;
import com.freeager.atomikos.test.service.UserService;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private BalanceLogService balanceLogService;

    @Override
    @Transactional(readOnly = false)
    public Integer banlance(Long userId, Integer type, Integer balance) {
	User user = new User();
	user.setId(userId);
	user = userMapper.selectOne(user);

	if (type == -1) {
	    if (user.getBalance() < balance) {
		throw new IllegalArgumentException("余额不够");
	    }
	    user.setBalance(user.getBalance() - balance);
	} else {
	    user.setBalance(user.getBalance() + balance);
	}
	return userMapper.updateByPrimaryKey(user);
    }

    @Override
    @Transactional(readOnly = false)
    public Integer test(Long userId, Integer type, Integer balance) {
	balanceLogService.addLog(userId, type, balance);
	return banlance(userId, type, balance);
    }

}
